package com.qyhl.webtv.module_circle.circle.detail;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.basiclib.utils.dialog.SingleChoiceDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.Image;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.service.IntergralService;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.NineGridLayout.NineAdapter;
import com.qyhl.webtv.commonlib.utils.view.NineGridLayout.NineLayout;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.qyhl.webtv.commonlib.utils.view.scrollview.FullyLinearLayoutManager;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.qyhl.webtv.module_circle.circle.msg.chat.ChatMessageActivity;
import com.qyhl.webtv.module_circle.utils.LinkMovementClickMethod;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.leancloud.chatkit.utils.LCIMConstants;
import es.dmoral.toasty.Toasty;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;


/**
 * Created by qyhl on 2018/1/29.
 */

@Route(path = ARouterPathConstant.CIRCLE_DETAIL)
public class CircleDetailActivity extends BaseActivity implements CircleDetailContract.CircleDetailView, BaseActivity.InputListener {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.editbar)
    EditBar editbar;
    @BindView(R2.id.head_icon)
    ImageView headIcon;
    @BindView(R2.id.nickName)
    TextView nickName;
    @BindView(R2.id.date)
    TextView publishDate;
    @BindView(R2.id.scan_num)
    TextView scanNum;
    @BindView(R2.id.to_chat)
    ImageView toChat;
    @BindView(R2.id.content)
    TextView mContent;
    @BindView(R2.id.nine_layout)
    NineLayout nineLayout;
    @BindView(R2.id.type_layout)
    RelativeLayout typeLayout;
    @BindView(R2.id.location)
    TextView location;
    @BindView(R2.id.praise_img)
    ImageView praiseImg;
    @BindView(R2.id.praise_txt)
    TextView praiseTxt;
    @BindView(R2.id.praise_layout)
    RelativeLayout praiseLayout;
    @BindView(R2.id.praise_content)
    TextView praiseContent;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.comment_layout)
    LinearLayout commentLayout;
    @BindView(R2.id.scrollview)
    ScrollView scrollview;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.comment_num)
    TextView commentNum;
    @BindView(R2.id.more)
    ImageView more;
    @BindView(R2.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R2.id.video_cover)
    ImageView videoCover;
    @BindView(R2.id.video_layout)
    RelativeLayout videoLayout;
    @BindView(R2.id.back_btn)
    ImageView backBtn;
    @BindView(R2.id.video_tag)
    ImageView videoTag;

    private CircleDetailPresenter mPresenter;
    private List<CircleHomeBean.PostList> mDataList;

    @Autowired(name = "id")
    String topicId;

    private EmptyWrapper emptyWrapper;

    private CommonAdapter mAdapter;

    private CircleHomeBean mBean;

    private String lastId = "0";

    private LoadingDialog.Builder builder;

    private String dstUserName;//回复对象账号

    private List<CircleHomeBean.User> loveList;//点赞用户集合

    private int loveCount;//点赞数

    private int postId;
    private boolean editbarEnabled = true;
    private boolean praiseEnabled = true;

    @Autowired(name = ServicePathConstant.INTERGRAL_SERICE)
    public IntergralService intergralService;

    @Override
    protected int getContentView() {
        return R.layout.circle_activity_circle_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mPresenter = new CircleDetailPresenter(this);
        initView();
        mPresenter.getDetail(topicId);
    }

    @Override
    protected void setListener() {
        setListeners();
    }

    @Override
    public void showkeyboard() {

    }

    @Override
    public void hideKeyboard() {
        editbar.changeStateDefault(this);
    }

    /**
     * 初始化
     */
    private void initView() {
        addInputListener(this);
        loadMask.setStatus(LoadingLayout.Loading);
        mDataList = new ArrayList<>();
        loveList = new ArrayList<>();

        builder = new LoadingDialog.Builder(CircleDetailActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        editbar.hideCollect(true);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        //设置布局管理器
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        mAdapter = new CommonAdapter<CircleHomeBean.PostList>(this, R.layout.circle_item_circle_detail_comment, mDataList) {

            @Override
            protected void convert(ViewHolder holder, final CircleHomeBean.PostList postList, final int position) {
                //头像
                ImageView head = holder.getView(R.id.head_icon);
                Glide.with(CircleDetailActivity.this)
                        .load(postList.getUser().getLogo())
                        .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default).transform(new GlideCircleTransform(CircleDetailActivity.this)))
                        .into(head);

                head.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Bundle bundle = new Bundle();
                        bundle.putString("dstusername", postList.getUser().getUsername());
                        RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);

                    }
                });
                //时间
                TextView date = holder.getView(R.id.publish_date);
                date.setText(DateUtils.mTranslateDate(postList.getGmtCreate()));

                //昵称
                TextView nickName = holder.getView(R.id.nickName);
                nickName.setText(postList.getUser().getNickName());

                //内容
                TextView content = holder.getView(R.id.content);
                SpanUtils spanUtils = new SpanUtils(CircleDetailActivity.this);
                if (postList.getType() == 1) {
                    spanUtils.append(postList.getContent()).setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_content));
                } else {
                    spanUtils.append("回复").setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_content))
                            .append(postList.getReply().getNickName()).setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_name))
                            .setClickSpan(new ClickableSpan() {
                                @Override
                                public void onClick(View widget) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("dstusername", postList.getReply().getUsername());
                                    RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);
                                }

                                @Override
                                public void updateDrawState(TextPaint ds) {
                                    //取消下划线
                                    ds.setUnderlineText(false);
                                }
                            })
                            .append(": " + postList.getContent()).setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_content));
                }
                content.setText(spanUtils.create());
                //开始响应点击事件
                content.setMovementMethod(LinkMovementClickMethod.getInstance());
                content.setFocusable(false);
            }
        };

        emptyWrapper = new EmptyWrapper(mAdapter);
        emptyWrapper.setEmptyView(R.layout.circle_layout_comment_emptyview);
        recyclerView.setAdapter(emptyWrapper);

    }

    /**
     * 监听
     */
    private void setListeners() {
        //评论
        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                //点击不是自己
                String userName = CommonUtils.getInstance().getUserName();
                if (!mDataList.get(position).getUser().getUsername().equals(userName)) {
                    editbar.changeStateSend(CircleDetailActivity.this);
                    dstUserName = mDataList.get(position).getUser().getUsername();
                    editbar.setEditTextHint("回复:" + mDataList.get(position).getUser().getNickName());
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, final int position) {
                //点击不是自己
                String userName = CommonUtils.getInstance().getUserName();
                if (!mDataList.get(position).getUser().getUsername().equals(userName)) {
                    new OtherDialog.Builder(CircleDetailActivity.this)
                            .setContentView(R.layout.circle_layout_dialog_other)
                            .setGravity(Gravity.BOTTOM)
                            .setCancelable(true)
                            .setCanceledOnTouchOutside(true)
                            .setOnClickListener(R.id.complain, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                        @Override
                                        public void login(boolean isLogin) {
                                            if (isLogin) {
                                                Bundle bundle = new Bundle();
                                                bundle.putString("type", "2");
                                                bundle.putString("id", mDataList.get(position).getId() + "");
                                                RouterManager.router(ARouterPathConstant.CIRCLE_COMPLAIN, bundle);
                                            } else {
                                                Toasty.normal(CircleDetailActivity.this, "尚未登录或登录已失效！").show();
                                                RouterManager.routerLogin(CircleDetailActivity.this, 0);
                                            }
                                        }

                                        @Override
                                        public void error(String s) {

                                        }
                                    });
                                }
                            }).show();
                } else {
                    postId = mDataList.get(position).getId();
                    new OtherDialog.Builder(CircleDetailActivity.this)
                            .setContentView(R.layout.circle_layout_dialog_delete)
                            .setGravity(Gravity.BOTTOM)
                            .setOnClickListener(R.id.delete, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                        @Override
                                        public void login(boolean isLogin) {
                                            if (isLogin) {
                                                mPresenter.deleteComment(postId + "");
                                            } else {
                                                Toasty.normal(CircleDetailActivity.this, "尚未登录或登录已失效！").show();
                                                RouterManager.routerLogin(CircleDetailActivity.this, 0);
                                            }
                                        }

                                        @Override
                                        public void error(String s) {

                                        }
                                    });

                                }
                            }).show();
                }
                return true;
            }
        });

        //刷新
        refresh.setOnRefreshListener(refreshlayout -> mPresenter.getDetail(topicId));

        //加载
        refresh.setOnLoadMoreListener(refreshlayout -> {
            if (mDataList.size() > 0) {
                mPresenter.getComment(topicId, lastId);
            } else {
                refresh.finishLoadMore();
            }
        });

        //重载
        loadMask.setOnReloadListener(v -> mPresenter.getDetail(topicId));

        //头像点击
        headIcon.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString("dstusername", mBean.getUser().getUsername());
                    RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);
                }
        );

        //返回
        backBtn.setOnClickListener(v -> finish());

        //跳转聊天
        toChat.setOnClickListener(v -> {
            toChat.setEnabled(false);

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        if (toChat.getDrawable().getCurrent().getConstantState().equals(ContextCompat.getDrawable(CircleDetailActivity.this, R.drawable.circle_follow_off).getConstantState())) {
                            mPresenter.doFollow(mBean.getUser().getUsername());
                        } else {
                            mPresenter.checkShield(mBean.getUser().getUsername());
                        }
                    } else {
                        Toasty.normal(CircleDetailActivity.this, "尚未登录或登录已失效！").show();
                        RouterManager.routerLogin(CircleDetailActivity.this, 0);
                    }
                    toChat.setEnabled(true);
                }

                @Override
                public void error(String s) {
                    toChat.setEnabled(true);
                }
            });
        });

        //点赞
        praiseLayout.setOnClickListener(v -> {
            if (praiseEnabled) {
                praiseEnabled = false;

                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            if (praiseImg.getDrawable().getCurrent().getConstantState().equals(ContextCompat.getDrawable(CircleDetailActivity.this, R.drawable.circle_detail_praise_off).getConstantState())) {
                                mPresenter.doLove(mBean.getId() + "");
                            } else {
                                mPresenter.undoLove(mBean.getId() + "");
                            }
                        } else {
                            Toasty.normal(CircleDetailActivity.this, "尚未登录或登录已失效！").show();
                            RouterManager.routerLogin(CircleDetailActivity.this, 0);
                            praiseEnabled = true;
                        }
                    }

                    @Override
                    public void error(String s) {
                        praiseEnabled = true;
                    }
                });
            }
        });
        editbar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {
                if (editbarEnabled) {
                    editbarEnabled = false;

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            String content = editbar.getContent();
                            if (StringUtils.isEmpty(content)) {
                                Toasty.normal(CircleDetailActivity.this, "评论内容不能为空！", Toast.LENGTH_SHORT).show();
                                editbarEnabled = true;
                            } else {
                                mPresenter.sendMessage(topicId, content, dstUserName);
                                hideInput();//隐藏软键盘
                            }
                            editbar.clearContent();
                        }

                        @Override
                        public void error(String s) {
                            editbarEnabled = true;
                        }
                    });

                }
            }

            @Override
            public void onShare() {
                MPermissionUtils.requestPermissionsResult(CircleDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        String shareIcon;
                        switch (mBean.getType()) {
                            case 1:
                                shareIcon = null;
                                break;
                            case 2:
                                try {
                                    shareIcon = mBean.getPicList().get(0).getThumb();
                                } catch (Exception e) {
                                    shareIcon = null;
                                }
                                break;
                            case 3:
                                shareIcon = mBean.getVideoThumb();
                                break;
                            default:
                                shareIcon = null;
                                break;
                        }
                        MShareBoard shareBoard = new MShareBoard(CircleDetailActivity.this, mBean.getId() + "", "来自" + mBean.getUser().getNickName() + "的朋友圈", shareIcon, mBean.getContent(), CommonUtils.getInstance().getBannerId(), 15);
                        shareBoard.showPopupWindow();
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(CircleDetailActivity.this);
                    }
                });
            }

            @Override
            public void onComment() {
                int[] location = new int[2];
                commentNum.getLocationInWindow(location);
                scrollview.scrollTo(0, location[1]);
            }
        });

        //更多
        more.setOnClickListener(v ->
                new SingleChoiceDialog.Builder(CircleDetailActivity.this).setTitle("是否删除该帖子", R.color.global_gray_lv2)
                        .addList(new String[]{"删除"})
                        .setCancelTextColor(R.color.global_base)
                        .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                            @Override
                            public void OnItemClick(String title, int position) {
                                switch (position) {
                                    case 0:
                                        mPresenter.deleteTopic(mBean.getId() + "");
                                        break;
                                    default:
                                        break;
                                }
                            }
                        })
                        .show());

    }

    @Override
    public void checkPass() {
        Intent intent = new Intent(CircleDetailActivity.this, ChatMessageActivity.class);
        intent.putExtra(LCIMConstants.PEER_ID, mBean.getUser().getUsername());
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void checkUnPass(String msg) {
        Toasty.normal(this, msg).show();
    }

    /**
     * 设置详情
     *
     * @param bean
     */
    @Override
    public void setDetail(final CircleHomeBean bean) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");

        mBean = bean;
        title.setText("");

        String userName = CommonUtils.getInstance().getUserName();
        if (mBean.getUser().getUsername().equals(userName)) {
            more.setVisibility(View.VISIBLE);
        } else {
            more.setVisibility(View.GONE);
        }

        //头像
        Glide.with(this)
                .load(mBean.getUser().getLogo())
                .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default).transform(new GlideCircleTransform(this)))
                .into(headIcon);

        //昵称
        nickName.setText(mBean.getUser().getNickName());
        String userNameS = CommonUtils.getInstance().getUserName();
        if (mBean.getUser().getUsername().equals(userNameS)) {
            toChat.setVisibility(View.GONE);
        } else {
            toChat.setVisibility(View.VISIBLE);
            //关注状态
            if (mBean.isFollow()) {
                toChat.setImageResource(R.drawable.circle_detail_chat);
            } else {
                toChat.setImageResource(R.drawable.circle_follow_off);
            }
        }

        //点赞状态
        if (mBean.isLove()) {
            praiseImg.setImageResource(R.drawable.circle_detail_praise_on);
            praiseTxt.setText("爱你么么哒~");
        } else {
            praiseImg.setImageResource(R.drawable.circle_detail_praise_off);
            praiseTxt.setText("赞我~");
        }

        //地址
        if (StringUtils.isNotEmpty(bean.getPosition())) {
            location.setVisibility(View.VISIBLE);
            location.setText(bean.getPosition());
        } else {
            location.setVisibility(View.GONE);
        }

        //评论人数
        commentNum.setText(new SpanUtils(this)
                .append("(").setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_content))
                .append(mBean.getPostCount() + "").setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_name))
                .append(")").setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_content))
                .create());

        //点赞过的人
        loveList = mBean.getLoverUser();
        loveCount = mBean.getLoveCount();
        setPraise(loveList, loveCount);

        //发布时间
        publishDate.setText(DateUtils.mTranslateDate(mBean.getGmtCreate()));

        //描述
        String content = mBean.getContent();
        //多文本样式工具类
        SpanUtils spanUtils = new SpanUtils(this);
        if (bean.getPriority() != 1) {
            spanUtils.appendImage(R.drawable.circle_top, SpanUtils.ALIGN_CENTER).appendSpace(10);
        }
        for (int i = 0; i < mBean.getTagList().size(); i++) {
            String tag = "#" + mBean.getTagList().get(i).getName() + "#";
            final int finalI = i;
            spanUtils.append(tag).setSpans(new TextAppearanceSpan(this, R.style.circle_content_tag)).setClickSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    //跳转到话题--------------------------------------
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mBean.getTagList().get(finalI).getId() + "");
                    RouterManager.router(ARouterPathConstant.CIRCLE_TOPIC, bundle);
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);//取消下划线
                }
            });
        }
        spanUtils.append(content).setSpans(new TextAppearanceSpan(this, R.style.circle_content_txt));
        mContent.setText(spanUtils.create());
        mContent.setMovementMethod(LinkMovementMethod.getInstance());
        mContent.setFocusable(false);

        //1.文本  2.图片  3.视频
        if (mBean.getType() == 1) {
            typeLayout.setVisibility(View.GONE);
        } else if (mBean.getType() == 2) {
            typeLayout.setVisibility(View.VISIBLE);
            videoLayout.setVisibility(View.GONE);
            nineLayout.setVisibility(View.VISIBLE);

            nineLayout.setGap(10);
            final List<Image> imageList = initDatas(bean.getPicList());
            Adapter adapter = new Adapter(this, imageList);
            nineLayout.setAdapter(adapter);
            nineLayout.setOnItemClickListerner(new NineLayout.OnItemClickListerner() {
                @Override
                public void onItemClick(View view, int position) {

                    ArrayList<String> mList = new ArrayList<>();
                    for (int i = 0; i < bean.getPicList().size(); i++) {
                        mList.add(bean.getPicList().get(i).getImage());
                    }
                    MNImageBrowser.showImageBrowser(CircleDetailActivity.this, view, position, mList);
                }
            });
        } else {
            typeLayout.setVisibility(View.VISIBLE);
            videoLayout.setVisibility(View.VISIBLE);
            nineLayout.setVisibility(View.GONE);

            ViewGroup.LayoutParams params = videoCover.getLayoutParams();
            if (StringUtils.isNotEmpty(bean.getVideoHeight()) && StringUtils.isNotEmpty(bean.getVideoWidth())) {
                if (Integer.parseInt(bean.getVideoWidth()) > Integer.parseInt(bean.getVideoHeight())) {
                    params.width = Integer.parseInt(bean.getVideoWidth()) > 600 ? 600 : Integer.parseInt(bean.getVideoWidth());
                    params.height = params.width * 9 / 16;
                } else {
                    params.height = Integer.parseInt(bean.getVideoHeight()) > 600 ? 600 : Integer.parseInt(bean.getVideoHeight());
                    params.width = params.height * 9 / 16;
                }
            } else {
                params.height = 600;
                params.width = params.height * 9 / 16;
            }

            videoCover.setLayoutParams(params);

            Glide.with(this).load(mBean.getVideoThumb()).into(videoCover);

            videoCover.setOnClickListener(v -> {

                Bundle bundle = new Bundle();
                bundle.putString(IntentKey_VideoUrl, mBean.getVideo());
                bundle.putString(IntentKey_VideoCover, mBean.getVideoThumb());
                RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);

            });

        }

        if (mBean.getPostList() != null && mBean.getPostList().size() > 0) {
            lastId = mBean.getPostList().get(mBean.getPostList().size() - 1).getId() + "";
        }


        //评论
        mDataList.clear();
        mDataList.addAll(mBean.getPostList());

        mAdapter.notifyDataSetChanged();
        emptyWrapper.notifyDataSetChanged();
    }

    @Override
    public void setComment(List<CircleHomeBean.PostList> beanList) {
        refresh.finishLoadMore();

        if (beanList != null && beanList.size() > 0) {
            lastId = beanList.get(beanList.size() - 1).getId() + "";
        }

        mDataList.addAll(beanList);

        mAdapter.notifyDataSetChanged();
        emptyWrapper.notifyDataSetChanged();
        editbarEnabled = true;
    }

    @Override
    public void setCommentError(String msg) {
        refresh.finishLoadMore();
        Toasty.normal(this, msg);
        editbarEnabled = true;
    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setErrorText(msg);
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setNoNetworkText(msg);
    }

    @Override
    public void followSuccess(String msg) {
        Toasty.normal(this, msg).show();
        toChat.setImageResource(R.drawable.circle_detail_chat);
    }

    @Override
    public void followError(String msg) {
        Toasty.normal(this, msg).show();
    }

    @Override
    public void doLoveSuccess() {
        String userName = CommonUtils.getInstance().getUserName();
        praiseImg.setImageResource(R.drawable.circle_detail_praise_on);
        praiseTxt.setText("爱你么么哒~");
        BusFactory.getBus().post(new Event.praiseRefreshEvent(mBean.getId(), 1));
        String nickName = CommonUtils.getInstance().getNickName();
        loveList.add(0, new CircleHomeBean.User(nickName, "", userName, false));
        loveCount++;
        setPraise(loveList, loveCount);
        praiseEnabled = true;
    }

    @Override
    public void doLoveError(String msg) {
        Toasty.normal(this, msg).show();
        praiseEnabled = true;
    }

    @Override
    public void undoLoveSuccess() {
        praiseImg.setImageResource(R.drawable.circle_detail_praise_off);
        praiseTxt.setText("赞我~");
        BusFactory.getBus().post(new Event.praiseRefreshEvent(mBean.getId(), 0));
        String userName = CommonUtils.getInstance().getUserName();
        for (int i = 0; i < loveList.size(); i++) {
            if (loveList.get(i).getUsername().equals(userName)) {
                loveList.remove(i);
            }
        }
        loveCount--;
        setPraise(loveList, loveCount);
        praiseEnabled = true;
    }

    @Override
    public void undoLoveError(String msg) {
        Toasty.normal(this, msg).show();
        praiseEnabled = true;
    }

    /**
     * 评论成功
     *
     * @param msg
     * @param code
     */
    @Override
    public void commentSuccess(String msg, int code) {
        builder.dismiss();
        Toasty.normal(this, msg).show();

        editbar.clearContent();
        editbar.changeStateDefault(this);
        hideInput();

        //评论人数
        commentNum.setText(new SpanUtils(this)
                .append("(").setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_content))
                .append(mBean.getPostCount() + 1 + "").setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_name))
                .append(")").setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_content))
                .create());
        if (mDataList.size() > 0) {
            mPresenter.getComment(topicId, lastId);
        }

        String integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        if (integralSwitch.equals("1")) {
            getCommentCoin();
        }
    }

    /**
     * 评论失败
     *
     * @param msg
     */
    @Override
    public void commentError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg).show();
        editbarEnabled = true;
    }

    /**
     * 评论获取金币
     */
    private void getCommentCoin() {

        intergralService.gainCoin("7", "gainCoin", new IntergralService.GainCoinCallBack() {
            @Override
            public void success(CoinBean coinBean) {
                Toasty.normal(CircleDetailActivity.this, "成功评论，获得" + coinBean.getCoin() + "金币！").show();
            }

            @Override
            public void error(String msg) {
                Log.i("coin_error", msg);
            }
        });
    }

    @Override
    public void deleteSuccess() {
        for (int i = 0; i < mDataList.size(); i++) {
            if (mDataList.get(i).getId() == postId) {
                mDataList.remove(i);
            }
        }
        emptyWrapper.notifyDataSetChanged();
    }

    @Override
    public void deleteError(String msg) {
        Toasty.normal(this, msg).show();
    }

    @Override
    public void deleteTopicSuccess() {
        Toasty.normal(this, "删除成功！").show();
        BusFactory.getBus().post(new Event.circleRefresh(mBean.getId()));
        finish();
    }

    @Override
    public void deleteTopicError(String msg) {
        Toasty.normal(this, msg).show();
    }


    //生成九宫格模型
    private List<Image> initDatas(List<CircleHomeBean.PicList> beanList) {
        List<Image> images = new ArrayList<>();
        if (beanList.size() == 1) {
            images.add(new Image(beanList.get(0).getThumb(), beanList.get(0).getWidth(), beanList.get(0).getHeight()));
        } else {
            for (int i = 0; i < beanList.size(); i++) {
                images.add(new Image(beanList.get(i).getThumb(), 0, 0));
            }
        }
        return images;
    }

    class Adapter extends NineAdapter {

        public Adapter(Context context, List<Image> list) {
            super(context, list);
        }

        @Override
        public int getCount() {
            return (list == null) ? 0 : list.size();
        }

        @Override
        public String getUrl(int position) {
            return getItem(position) == null ? null : ((Image) getItem(position)).getUrl();
        }

        @Override
        public Object getItem(int position) {
            return (list == null) ? null : list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int i, View view) {
            ImageView iv = new ImageView(context);
            Glide.with(context)
                    .load(list.get(i).getUrl())
                    .apply(new RequestOptions().error(R.drawable.cover_normal_default).centerCrop().optionalTransform(new GlideRoundTransform(4)))
                    .into(iv);
            return iv;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (editbar.getType() == EditBar.TYPE_SEND) {//判断是否是输入状态，是则返回初始状态，否则退出
                    editbar.clearContent();
                    editbar.changeStateDefault(this);
                    return true;
                } else if (GSYVideoManager.backFromWindowFull(this)) {
                    return true;
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置点赞
     */
    private void setPraise(List<CircleHomeBean.User> beanList, int loveCount) {
        if (beanList != null && beanList.size() > 0) {
            praiseContent.setVisibility(View.VISIBLE);
            final SpanUtils utils = new SpanUtils(this);
            utils.appendImage(R.drawable.circle_praise_on, SpanUtils.ALIGN_CENTER);

            final String praiseNum = "等" + StringUtils.transformNum(loveCount + "") + "人觉得很赞";

            int max;
            if (beanList.size() > 10) {
                max = 10;
            } else {
                max = beanList.size();
            }
            for (int i = 0; i < max; i++) {
                if (i == (max - 1)) {
                    final int finalI = i;
                    utils.append(beanList.get(i).getNickName()).setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_name)).setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Bundle bundle = new Bundle();
                            bundle.putString("dstusername", mBean.getLoverUser().get(finalI).getUsername());
                            RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            //取消下划线
                            ds.setUnderlineText(false);
                        }
                    }).append(praiseNum).setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_content));
                } else {
                    final int finalI = i;
                    utils.append(beanList.get(i).getNickName() + "、").setSpans(new TextAppearanceSpan(CircleDetailActivity.this, R.style.circle_comment_name)).setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Bundle bundle = new Bundle();
                            bundle.putString("dstusername", mBean.getLoverUser().get(finalI).getUsername());
                            RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);

                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            //取消下划线
                            ds.setUnderlineText(false);
                        }
                    });
                }
            }

            praiseContent.setText(utils.create());
            praiseContent.setMovementMethod(LinkMovementMethod.getInstance());
            praiseContent.setFocusable(false);
        } else {
            praiseContent.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("圈子详情");
        MobclickAgent.onResume(this);
        ActionLogUtils.getInstance().onResume(this, ActionConstant.CIRCLEDETAIL);
    }

    @Override
    public void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("圈子详情");
        MobclickAgent.onPause(this);

        ActionLogUtils.getInstance().onPause(this, ActionConstant.CIRCLEDETAIL);
    }

    /**
     * 登录状态改变事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        String userName = CommonUtils.getInstance().getUserName();
        if (event != null) {
            if (mBean.getUser().getUsername().equals(userName)) {
                more.setVisibility(View.VISIBLE);
            } else {
                more.setVisibility(View.GONE);
            }
        }
    }


}
